# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os, random
import requests
from uoco import settings
from .user_agents import agents


class UocoPipeline(object):
    def process_item(self, item, spider):
        return item


# 图片下载类
# class ImageDownloadPipeline(object):
#     def __init__(self):
#         if os.path.exists(settings.IMAGES_STORE) == False:
#             os.mkdir(settings.IMAGES_STORE)
#
#     def process_item(self, item, spider):
#         ext = item['image_url'].split('.')[-1]
#         with open(settings.IMAGES_STORE + item['name'] + '.' + ext, 'wb') as f:
#             response = requests.get(item['image_url'], stream=True)
#             f.write(response.content)
#         return item

class ImageDownloadPipeline(object):
    def __init__(self):
        if os.path.exists(settings.IMAGES_STORE) == False:
            os.mkdir(settings.IMAGES_STORE)

    def process_item(self, item, spider):
        cnt = 0
        for img in item['image_urls']:
            cnt = cnt + 1
            ext = img.split('.')[-1]
            with open(settings.IMAGES_STORE + item['name'] + str(cnt) + '.' + ext, 'wb') as f:
                agent = random.choice(agents)
                headers = {
                    'User-Agent': agent,
                }
                response = requests.get(img, headers=headers, stream=True, timeout=1)
                f.write(response.content)
